﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using hzGis.service;
using hzGis.service.impl;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using hzGis.utils;
using hzGis.config;
using hzGis.Component;
using System.IO;
using hzGis.model;

namespace hzGis
{
    public partial class YdbpWin : Form
    {
        private IFileService fileService;
        private IStyleService styleSerivce;
        private MapToolService mapToolService;
        private LayerOutService layerOutService;
        private PrintService printService;
        private AnalysisService analysisService;
        private IAnalysisDlService analysisDlService;
        private IDBService dbService;
        private IPdfSevice pdfService;
        
        private IElement titleElement;
        private IElement tfhElement;
        private IElement tlElement;
        private IElement bzElement;
        private IElement bzInfoElement;
        private int maxYear;
        private string xmmc;
        private string ztry;
        private string bphxFile = "D:\\data\\bphx.shp";
        private string fxjgFile = "D:\\code\\Hz\\ydbp\\data\\bpdl4547.shp";
        private ToolConfig toolConfig;
        private IPoint defaultCeneter;
        private string bpShp;
        private string fxjgShp;
        private YdbpXm ydbpXm;
        private string code;
        private long id;
        private double pageW = 29.7 * 2;
        private double pageH = 21.0 * 2;
        private double outMinx = 0;
        private double outMiny = 0;
        private double outMaxx = 0;
        private double outMaxy = 0;
        private double mapMinx = 0;
        private double mapMaxx = 0;
        private double mapMiny = 0;
        private double mapMaxy = 0;
        private double arrowMinx = 0;
        private double arrowMiny = 0;
        private double arrowMaxx = 0;
        private double arrowMaxy = 0;
        private double legendMaxx = 12.5;
        private double legendMaxy = 12;
        private Dictionary<string, ITextElement> lineNumElements = new Dictionary<string,ITextElement>();
        public YdbpWin(string code)
        {
            InitializeComponent();
            initData();
            fileService = new FileService();
            styleSerivce = new StyleService();
            mapToolService = new MapToolService();
            layerOutService = new LayerOutService();
            printService = new PrintService();
            analysisService = new AnalysisService();
            analysisDlService = new AnalysisDlService();
            pdfService = new PdfService();
            dbService = new DBService();
            
            xmmc = "赣深高铁惠州北站片区防洪排涝工程(一期)惠城段项目2021年度土地利用现状图";
            ztry = "卢柱佑";
            string dirPath = fileService.getCurrentPath();
            string configPath = dirPath + "\\" + SysConfig.CONFIGNAME;
            ToolConfig toolConfig2 = null;
            if (!File.Exists(configPath))
            {
                MessageBox.Show(SysConfig.NO_CONFIG);
                return;
            }
            toolConfig2 = JsonHelper.JsonDeserialize<ToolConfig>(File.ReadAllText(configPath));
            this.code = code;
            try
            {
                intWin(toolConfig2);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.StackTrace);
            }
            
        }
        private void initData()
        {
            outMinx = 2;
            outMiny = 2;
            outMaxx = pageW - 2.4;
            outMaxy = pageH - 2.8;
            mapMinx = 3;
            mapMiny = 3;
            mapMaxx = pageW - 3.4;
            mapMaxy = pageH - 3.8;
            arrowMinx = pageW - 5.1;
            arrowMiny = pageH - 7.7;
            arrowMaxx = pageW - 3.4;
            arrowMaxy = pageH - 3.8;
        }

        private void clearLayers(IMap map, string[] names)
        {
            for (var i = 0; i < map.LayerCount; i++)
            {
                ILayer layer = map.get_Layer(i);
                for(var j = 0; j < names.Length; j++) {
                    if (layer.Name == names[j]) {
                        map.DeleteLayer(layer);
                    }
                }
            }
        }
        private void clearAllLayers(IMap map)
        {
            for (var i = 0; i < map.LayerCount; i++)
            {
                ILayer layer = map.get_Layer(i);
                map.DeleteLayer(layer);
            }
        }
        private string checkToolConfig(ToolConfig t_toolConfig)
        {
            string message = "";
            if (t_toolConfig.cjLyr != "")
            {
                if (!File.Exists(t_toolConfig.cjLyr))
                {
                    message += "当前村界lyr文件不存在\r\n";
                }
            }
            else
            {
                message += "当前村界lyr文件不存在\r\n";
            }
            if (t_toolConfig.dbName== null || t_toolConfig.dbName == "")
            {
                message += "请输入数据库名称\r\n";
            }
            if (t_toolConfig.dbPort == null || t_toolConfig.dbPort == "")
            {
                message += "请配置数据库端口\r\n";
            }
            if (t_toolConfig.dbPwd == null || t_toolConfig.dbPwd == "")
            {
                message += "请输入数据库密码\r\n";
            }
            if (t_toolConfig.dbUrl == null || t_toolConfig.dbUrl == "")
            {
                message += "请配置数据库链接\r\n";
            }
            if (t_toolConfig.dbUser == null || t_toolConfig.dbUser == "")
            {
                message += "请配置数据库用户名\r\n";
            }
            if (t_toolConfig.dl == null || t_toolConfig.dl == "")
            {
                message += "请设置地类数据存在文件夹\r\n";
            }
            if (t_toolConfig.dlJsonFile == null || t_toolConfig.dlJsonFile == "")
            {
                message += "请设置建设用地json文件\r\n";
            }
            else
            {
                if (!File.Exists(t_toolConfig.dlJsonFile))
                {
                    message += "当前建设用地json文件不存在\r\n";
                }
            }
            if (t_toolConfig.fxTl == null || t_toolConfig.fxTl == "")
            {
                message += "请设置分析图例图片\r\n";
            }
            else {
                if (!File.Exists(t_toolConfig.fxTl))
                {
                    message += "当前分析图例图片不存在\r\n";
                }
            }
            if (t_toolConfig.resultLj == null || t_toolConfig.resultLj == "")
            {
                message += "请配置结果存放路径\r\n";
            }
            if (t_toolConfig.scale == null || t_toolConfig.scale == "")
            {
                message += "请配置地图显示比例尺\r\n";
            }
            if (t_toolConfig.tfh == null || t_toolConfig.tfh == "")
            {
                message += "请配置图幅号shpfile路径\r\n";
            }
            else
            {
                if (!File.Exists(t_toolConfig.tfh))
                {
                    message += "请配置图幅号shpfile路径\r\n";
                }
            }
            if (t_toolConfig.xqShp == null || t_toolConfig.xqShp == "")
            {
                message += "请配置县区shpfile路径\r\n";
            }
            else
            {
                if (!File.Exists(t_toolConfig.xqShp))
                {
                    message += "请配置县区shpfile路径\r\n";
                }
            }
            if (t_toolConfig.xztl == null || t_toolConfig.xztl == "")
            {
                message += "请配置现状分析图例\r\n";
            }
            else {
                if (!File.Exists(t_toolConfig.xztl))
                {
                    message += "请配置现状分析图例\r\n";
                }
            }
            if (t_toolConfig.zjLyr == null || t_toolConfig.zjLyr == "")
            {
                message += "请配置镇街Lyr\r\n";
            }
            else
            {
                if (!File.Exists(t_toolConfig.zjLyr))
                {
                    message += "请配置镇街Lyr\r\n";
                }
            }
            return message;
        }
        public void intWin(ToolConfig t_toolConfig)
        {

            toolConfig = t_toolConfig;
            string message = checkToolConfig(toolConfig);
            if (message != "")
            {
                MessageBox.Show(message);
                return;
            }
            if (this.code != null && this.code !="")
            {
                string sid = code.Substring(code.IndexOf("//") + 2, code.Length - code.IndexOf("//") - 3);
                id = Convert.ToInt32(sid);
                this.ydbpXm = dbService.queryYdbpXmById(toolConfig, id);
                if (this.ydbpXm != null)
                {
                    this.xmmc = this.ydbpXm.xmmc;
                    this.ztry = this.ydbpXm.hty;
                    this.bphxFile = this.ydbpXm.bphxShp;
                    this.fxjgFile = this.ydbpXm.fxjgFile;
                }
            }
            this.clearAllLayers(this.axMapControl.Map);
            loadDefaultLayer(bphxFile, fxjgFile);
            
            initPageLayerout();
            // 设置默认显示比例尺
            this.axMapControl.Map.MapScale = Convert.ToInt16(toolConfig.scale);
            this.axMapControl.ActiveView.Refresh();
            this.mapToolService.CopyToPageLayout(this.axMapControl, this.axPageLayoutControl);
        }
        /// <summary>
        /// 鼠标在地图上点击时事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axMapControl_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e)
        {
            if (e.button == 4)
            {
                axMapControl.Pan();
                mapToolService.CopyToPageLayout(axMapControl, axPageLayoutControl);
            }
                
            
        }
        /// <summary>
        /// 当地图上的数据变化时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axMapControl_onMapReplaced(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMapReplacedEvent e)
        {

        }

        /// <summary>
        /// 当地图视图刷新时触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axMapControl_onViewRefreshed(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnViewRefreshedEvent e)
        {

        }

        /// <summary>
        /// 当地图视图被绘制后触发的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void axMapControl_onAfterScreenDraw(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnAfterScreenDrawEvent e)
        {
           
            
        }

        private void initPageLayerout()
        {
            mapToolService.CopyToPageLayout(axMapControl, axPageLayoutControl);
            IMap map = this.axPageLayoutControl.ActiveView.FocusMap;
            // 设置布局
            layerOutService.setLayerOutHorizontal(this.axPageLayoutControl, outMinx, outMiny, outMaxx, outMaxy, mapMinx, mapMiny, mapMaxx, mapMaxy, pageW, pageH, 1);
            // 添加指北针
            printService.AddNorthArrow(this.axPageLayoutControl.PageLayout, map, arrowMinx, arrowMiny, arrowMaxx, arrowMaxy, "esriCarto.MarkerNorthArrow");
            addDefaultLabel();
        }

        /// <summary>
        /// 默认加载指定的数据图层
        /// </summary>

        private void loadDefaultLayer(string bphx, string fxjg)
        {
            this.bpShp = bphx;
            this.fxjgShp = fxjg;
            // 加载地类数据
            // 加载镇界
            axMapControl.AddLayerFromFile(toolConfig.zjLyr, 0);
            // 加载村界
            axMapControl.AddLayerFromFile(toolConfig.cjLyr, 1);
            // 加载地类
            // 加载报批数据
            
            Dictionary<string, object> result = fileService.openShpFilePro(this.bpShp, this.axMapControl);
            
            ILayer bpLayer = result["layer"] as ILayer;
            defaultCeneter = result["center"] as IPoint;
                // 首先获取需要加载地类存在那些县区
            IFeatureClass xzqFeatureClass = fileService.openFeatureClassByShp(toolConfig.xqShp);
            
            List<string> xzqs = analysisDlService.anslysisXzq(xzqFeatureClass, ((IFeatureLayer)bpLayer).FeatureClass);
                // 基于分析结果获取最新年份
            
            IFeatureClass resultFeatureClass = fileService.openFeatureClassByShp(this.fxjgShp);
           
            // 1.首先要获取结果shp中最新的年份
            maxYear = analysisDlService.analysisMaxYear(resultFeatureClass);
            
            for (var i = 0; i < xzqs.Count; i++)
            {
                string dirName = analysisDlService.getDirName(xzqs[i]);
                string dlShp = toolConfig.dl + "\\" + maxYear + "\\" + dirName + "\\DLTB.shp";
                if (!File.Exists(dlShp))
                {
                    MessageBox.Show(dlShp+"未存在!");
                    break;
                }
                Dictionary<string, object> dlResult = fileService.openShpFilePro(dlShp, this.axMapControl);
                ILayer dlLayer = dlResult["layer"] as ILayer;
                dlLayer.Name = dirName;
                styleSerivce.setStyle(dlLayer, new byte[] { 100, 100, 100 }, 0.3, new byte[] { 0, 0, 0, 0 });
                styleSerivce.setLabelStyle(dlLayer, "DLBM");
                this.axMapControl.Map.AddLayer(dlLayer);
            }
            this.axMapControl.CenterAt(defaultCeneter);
            styleSerivce.setStyle(bpLayer, new byte[] { 245, 4, 4 }, 1, new byte[] { 0, 0, 0, 0 });
            bpLayer.Name = SysConfig.BP_LAYER_NAME;
            this.axMapControl.Map.AddLayer(bpLayer);
        }
        
        /// <summary>
        /// 添加默认的数据
        /// </summary>
        /// <param name="hty"></param>
        private void addDefaultLabel()
        {
            printService.addTitle("绘图员：" + this.ztry, this.axPageLayoutControl, 4.3, 0.8, 4.8, 1.6, 20, new byte[] { 0, 0, 0 }, "hty");
            String htsj = System.DateTime.Now.ToString("yyyy年MM月dd日");
            printService.addTitle("制图时间：" + htsj, this.axPageLayoutControl, 6, 0.2, 6.5, 0.7, 20, new byte[] { 0, 0, 0 }, "ztsj");
            // 比例尺
            printService.addTitle("1:10000", this.axPageLayoutControl, 29.5, 0.8, 29.7, 1.6, 20, new byte[] { 0, 0, 0 }, "blc");
            printService.addTitle("盖章单位：", this.axPageLayoutControl, 29.5 * 2 - 10, 0.8, 29.5 * 2 - 5, 1.6, 20, new byte[] { 0, 0, 0 }, "gzdw");
            printService.addTitle("盖章日期：", this.axPageLayoutControl, 29.5 * 2 - 10, 0.2, 29.5 * 2 - 5, 0.7, 20, new byte[] { 0, 0, 0 }, "gzrq");
        }

        private void printBtn_Click(object sender, EventArgs e)
        {
            // 进度设置为0
            jdBar.Value = 0;
            // 首先添加对应的图例
            if (bzElement != null)
            {
                printService.deleteElement(this.axPageLayoutControl, bzElement);
            }
            if (bzInfoElement != null)
            {
                printService.deleteElement(this.axPageLayoutControl, bzInfoElement);
            }
            analysisDlService.changeLayerByYear(this.axMapControl, axPageLayoutControl, maxYear);
            if (tlElement != null)
            {
                IPictureElement picElement = (IPictureElement)tlElement;
                picElement.ImportPictureFromFile(toolConfig.xztl);
                this.axPageLayoutControl.ActiveView.Refresh();
            }
            else
            {
                tlElement = printService.addPicture(this.axPageLayoutControl, mapMinx, mapMiny, legendMaxx, legendMaxy, toolConfig.xztl);
            }
            List<string> xzPdfs = fgTf(xmmc, "xz", toolConfig.resultLj + "\\");
            // 这里合并pdf
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("fileName", "现状图地类图");
            data.Add("pdfs", xzPdfs);
            bool res = pdfService.merge(data, toolConfig.resultLj + "\\");
            if (res)
            {
                jdBar.Value = 100;
                //MessageBox.Show("现状图地类图打印完成;存放路径为" + toolConfig.resultLj + "\\现状图地类图.pdf");
                System.Diagnostics.Process.Start(toolConfig.resultLj + "\\现状图地类图.pdf");
            }
        }

        private List<string> fgTf(string title, string code, string saveDirPath)
        {
            List<string> pdfs = new List<string>();
            //获取当前的报批红线的外边框范围
            IEnumLayer pEnumLayer = this.axMapControl.Map.Layers;
            pEnumLayer.Reset();
            ILayer bpLayer = null;
            ILayer pFlayer = (ILayer)pEnumLayer.Next();
            double printW = 29.5 - 2.3;
            double printH = 20.6 - 2.3;
            int outJdValue = 80;
            while (pFlayer != null)
            {
                if (pFlayer.Name == SysConfig.BP_LAYER_NAME)
                { bpLayer = pFlayer; }
                pFlayer = (IFeatureLayer)pEnumLayer.Next();
            }
            if (bpLayer != null)
            {
                IFeatureLayer bpFeatureLayer = bpLayer as IFeatureLayer;
                // 首先获取ILayer的边框范围
                IFeatureClass featureClass = bpFeatureLayer.FeatureClass;
                IGeoDataset featureDataset = featureClass as IGeoDataset;
                IEnvelope featureExtent = featureDataset.Extent;
                double xmax = featureExtent.XMax;
                double xmin = featureExtent.XMin;
                double ymax = featureExtent.YMax;
                double ymin = featureExtent.YMin;
                double xDifference = xmax - xmin;
                double yDifference = ymax - ymin;
                // 将实际距离转换为图上距离（按照1:10000，100m = 1cm）
                int sjjl = Convert.ToInt32(toolConfig.scale) / 100;
                int printExtentX = (int)Math.Ceiling(xDifference / sjjl);
                int printExtentY = (int)Math.Ceiling(yDifference / sjjl);
                // 判断实际打印的地图范围与纸张范围的尺寸关系
                // 宽度小于纸张范围
                string titile = "";
                if (printExtentX < printW)
                {
                    if (printExtentY < printH)
                    {
                        // 打印范围大于地图范围
                        // 这里将设置为默认的图形中心
                        PageInfo rectange = new PageInfo();
                        List<PageInfo> rectanges = new List<PageInfo>();
                        rectange.center = defaultCeneter;
                        rectange.rectange = new double[] { xmin, xmax, ymin, ymax };
                        rectanges.Add(rectange);
                        printByPageInfo(title, rectanges, saveDirPath, code, pdfs, outJdValue);
                    }
                    else
                    {
                        // 打印范围宽度小于地图范围高度大于地图范围
                        int pages = printExtentY % (printH) == 0 ? (int)Math.Floor(printExtentY / printH) : (int)Math.Ceiling(printExtentY / printH);
                        double printXmin = xmin, printXmax = xmax, printYmin = ymin, printYmax = 0;
                        int itemOutJdValue = outJdValue;
                        if (pages > 1)
                        {
                           itemOutJdValue = outJdValue / (pages - 1);
                        }
                        List<PageInfo> rectanges = new List<PageInfo>();
                        for (int i = 0; i < pages; i++)
                        {
                            printYmin = ymin + i * printH * sjjl;
                            printYmax = ymin + (i + 1) * printH * sjjl;
                            IPoint center = analysisDlService.sumCenterByRectange(featureClass, printXmin, printXmax, printYmin, printYmax, 1, i, pages);
                            if (center != null)
                            {
                                PageInfo rectange = new PageInfo();
                                rectange.center = center;
                                rectange.rectange = new double[] { printXmin, printXmax, printYmin, printYmax };
                                rectanges.Add(rectange);
                            }
                        }
                        printByPageInfo(title,rectanges, saveDirPath, code, pdfs, outJdValue);
                    }
                }
                else
                {
                    if (printExtentY < printH)
                    {
                        // 打印范围宽度大于地图范围高度范围小于地图范围
                        // 1.首先计算对应的需要打印多少页
                        int pages = printExtentX % (printW) == 0 ? (int)(Math.Floor(printExtentX / (printW))) : (int)(Math.Floor(printExtentX / (printW)) + 1);
                        double printXmin = xmin, printXmax = 0, printYmin = ymin, printYmax = ymax;
                        int itemOutJdValue = outJdValue;
                        if (pages > 1)
                        {
                            itemOutJdValue = outJdValue / (pages - 1);
                        }
                        List<PageInfo> rectanges = new List<PageInfo>();
                        for (int i = 0; i < pages; i++)
                        {
                            printXmin = xmin + i * printW * sjjl;
                            printXmax = xmin + (i + 1) * printW * sjjl;
                            IPoint center = analysisDlService.sumCenterByRectange(featureClass, printXmin, printXmax, printYmin, printYmax, 2, i, pages);
                            if (center != null)
                            {
                                PageInfo rectange = new PageInfo();
                                rectange.center = center;
                                rectange.rectange = new double[] { printXmin, printXmax, printYmin, printYmax };
                                rectanges.Add(rectange);
                            }
                        }
                        printByPageInfo(title, rectanges, saveDirPath, code, pdfs, outJdValue);
                    }
                    else
                    {
                        // 打印范围宽度大于地图范围高度大于地图范围
                        int wPages = printExtentX % (printW) == 0 ? (int)(Math.Floor(printExtentX / (printW))) : (int)(Math.Floor(printExtentX / (printW)) + 1);
                        int hPages = printExtentY % (printH) == 0 ? (int)(Math.Floor(printExtentY / (printH))) : (int)(Math.Floor(printExtentY / (printH)) + 1);
                        int num = 0;
                        int itemOutJdValue = outJdValue / (wPages * hPages);
                        List<PageInfo> rectanges = new List<PageInfo>();
                        double printXmin = xmin, printXmax = 0, printYmin = ymin, printYmax = 0;
                        for (int i = 0; i < wPages; i++)
                        {
                            printXmin = xmin + i * printW * sjjl;
                            printXmax = xmin + (i + 1) * printW * sjjl;
                            for (int j = 0; j < hPages; j++)
                            {
                                printYmin = ymin + j * printH * sjjl;
                                printYmax = ymin + (j + 1) * printH * sjjl;
                                IPoint center = analysisDlService.sumCenterByRectange(featureClass, printXmin, printXmax, printYmin, printYmax, 3, num, wPages * hPages);
                                if (center != null)
                                {
                                    PageInfo rectange = new PageInfo();
                                    rectange.center = center;
                                    rectange.rectange = new double[] { printXmin, printXmax, printYmin, printYmax };
                                    rectanges.Add(rectange);
                                }
                                ++num;
                            }
                        }
                        printByPageInfo(title,rectanges, saveDirPath, code, pdfs, outJdValue);
                    }
                }
            }
            return pdfs;
        }

        private string getTfh(double xmin, double ymin, double xmax, double ymax)
        {
            IEnvelope envelope = new Envelope() as IEnvelope;
            envelope.XMin = xmin;
            envelope.XMax = xmax;
            envelope.YMin = ymin;
            envelope.YMax = ymax;
            IFeatureClass featureClass = fileService.openFeatureClassByShp(toolConfig.tfh);
            List<IFeature> features = analysisService.spaceAnalysis(envelope, featureClass, esriSpatialRelEnum.esriSpatialRelIntersects);
            string tfh = "";
            if (features.Count > 0)
            {
                int num = features[0].Fields.FindField("新图幅");
                for (var i = 0; i < features.Count; i++)
                {
                    IFeature feature = features[i];
                    String val = feature.get_Value(num);
                    tfh += val;
                    if (i != features.Count - 1)
                    {
                        tfh += "、";
                    }
                }
            }
            return tfh;
        }

        private void addTitle(string title, double xmin, double ymin, double xmax, double ymax, double fontSize)
        {
            IActiveView pActiveViewv = this.axPageLayoutControl.PageLayout as IActiveView;
            IGraphicsContainer pGraphicsContainer = pActiveViewv.GraphicsContainer;
            if (titleElement != null)
            {
                pGraphicsContainer.DeleteElement(titleElement);
            }
            titleElement = printService.addTitle(title, this.axPageLayoutControl, xmin, ymin, xmax, ymax, fontSize, new byte[] { 0, 0, 0 }, "title");
        }
        private void addTfh(string tfh, double xmin, double ymin, double xmax, double ymax, double fontSize)
        {
            IActiveView pActiveViewv = this.axPageLayoutControl.PageLayout as IActiveView;
            IGraphicsContainer pGraphicsContainer = pActiveViewv.GraphicsContainer;
            if (tfhElement != null)
            {
                pGraphicsContainer.DeleteElement(tfhElement);
            }
            tfhElement = printService.addTitle(tfh, this.axPageLayoutControl, xmin, ymin, xmax, ymax, fontSize, new byte[] { 0, 0, 0 }, "tfh");
        }

        private void updateView(double xmin, double ymin, double xmax, double ymax, string xmmc,IPoint center)
        {
            axMapControl.CenterAt(center);
            axMapControl.Map.MapScale = Convert.ToInt32(toolConfig.scale);
            mapToolService.CopyToPageLayout(axMapControl, axPageLayoutControl);
            string tfh = "1:10000图幅号" + getTfh(xmin, ymin, xmax, ymax);
            // 添加图幅号
            this.addTfh(tfh, 29.5 - (tfh.Length / 2) * 0.2, 21.0 * 2 - 3, 29.5 + (tfh.Length / 2) * 0.2, 21.0 * 2 - 2, 20);
            // 添加标题
            this.addTitle(xmmc, 29.5 - (xmmc.Length / 2) * 0.4, 21.0 * 2 - 2, 29.5 + (xmmc.Length / 2) * 0.4, 21.0 * 2 - 1, 30);
        }

        private void printBtnDl_Click(object sender, EventArgs e)
        {
            jdBar.Value = 0;
            IFeatureClass resultFeatureClass = fileService.openFeatureClassByShp(this.fxjgShp);
            IFeatureLayer resultFeatureLayer = new FeatureLayer();
            resultFeatureLayer.FeatureClass = resultFeatureClass;
            ILayer resultLayer = resultFeatureLayer as ILayer;
            resultLayer.Name = SysConfig.FXJG_LAYER_NAME;
            this.axMapControl.AddLayer(resultFeatureLayer);
            // 1.首先要获取结果shp中最新的年份
            int maxYear = analysisDlService.analysisMaxYear(resultFeatureClass);
            // 2.按照递减的方式查询两个年份之间获取多个IFeature
            List<Dictionary<string, object>> result = analysisDlService.analysisJsydByYear(resultFeatureClass, maxYear, toolConfig.dlJsonFile);
            if (tlElement != null)
            {
                IPictureElement picElement = (IPictureElement)tlElement;
                picElement.ImportPictureFromFile(toolConfig.fxTl);
                this.axPageLayoutControl.ActiveView.Refresh();
            }
            else
            {
                printService.addPicture(this.axPageLayoutControl, mapMinx, mapMiny, legendMaxx, legendMaxy, toolConfig.fxTl);
            }
            // 3.将多个IFeature转为featureClass叠加到地图上
            List<Dictionary<string, object>> allPdfs = new List<Dictionary<string, object>>();
            for (var i = 0; i < result.Count; i++)
            {
                Dictionary<string, object> analysisResult = result[i];
                int afterYear = (int)analysisResult["afterYear"];
                int beforeYear = (int)analysisResult["beforeYear"];
                double jsydArea = (double)analysisResult["jsydArea"];
                addBzElement(afterYear, beforeYear, jsydArea);
                bool res = analysisDlService.changeLayer(this.axMapControl, this.axPageLayoutControl, analysisResult, resultLayer, toolConfig.dl);
                if (res)
                {
                    List<string> pdfs = fgTf(xmmc + afterYear.ToString() + "年度土地利用现状图", afterYear.ToString(), toolConfig.resultLj + "\\");
                    Dictionary<string, object> allPdf = new Dictionary<string, object>();
                    allPdf.Add("afterYear", afterYear);
                    allPdf.Add("pdfs", pdfs);
                    allPdfs.Add(allPdf);
                }
                jdBar.Value = i * (80 / result.Count);
            }
            List<string> allPdfFiles = new List<string>();
            for (var i = allPdfs.Count - 1; i > -1; i--)
            {
                Dictionary<string, object> allPdf = allPdfs[i];
                List<string> pdfs = allPdf["pdfs"] as List<string>;
                for (var j = 0; j < pdfs.Count; j++)
                {
                    allPdfFiles.Add(pdfs[j]);
                }
            }
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("fileName", "涉及建设用地变更年度的土地利用现状图");
            data.Add("pdfs", allPdfFiles);
            bool mergePdfRes = pdfService.merge(data, toolConfig.resultLj + "\\");
            if (mergePdfRes)
            {
                jdBar.Value = 100;
               // MessageBox.Show("涉及建设用地变更年度的土地利用现状图打印完成,存放路径为" + toolConfig.resultLj + "\\涉及建设用地变更年度的土地利用现状图.pdf");
                System.Diagnostics.Process.Start(toolConfig.resultLj + "\\涉及建设用地变更年度的土地利用现状图.pdf");
            }
        }

        private void addBzElement(int afterYear, int beforeYear, double jsydArea)
        {
            Random rd = new Random();
            string area = String.Format("{0:N4}", jsydArea / 10000);
            if (bzElement == null)
            {
                bzElement = printService.addRectangle(this.axPageLayoutControl, mapMinx, 12.3, 13.1, 13.5, new byte[] { 55, 148, 31 }, 1, new byte[] { 55, 148, 31 });
            }
            if (bzInfoElement == null)
            {
                if (afterYear != 1999)
                {
                    bzInfoElement = printService.addTitle("绿色范围图斑为" + afterYear + "年1月1日以后，" + afterYear + "年12月31日之前\r\n变更为建设用地范围，面积为" + area + "公顷。", this.axPageLayoutControl, 2.4, 12.1, 13, 13, 12, new byte[] { 0, 0, 0 }, "info");
                }
                else
                {
                    bzInfoElement = printService.addTitle("绿色范围图斑为" + afterYear + "年\r\n变更为建设用地范围，面积为" + area + "公顷。", this.axPageLayoutControl, 2.4, 12.1, 13, 13, 12, new byte[] { 0, 0, 0 }, "info");
                }
                
            }
            else
            {
                ITextElement bzTextInfoElement = (ITextElement)bzInfoElement;
                if (afterYear != 1999)
                {
                    bzTextInfoElement.Text = "绿色范围图斑为" + afterYear + "年1月1日以后，" + afterYear + "年12月31日之前\r\n变更为建设用地范围，面积为" + area + "公顷。";
                }
                else
                {
                    bzTextInfoElement.Text = "绿色范围图斑为" + afterYear + "年\r\n变更为建设用地范围，面积为" + area + "公顷。";
                }
                
            }
            this.axPageLayoutControl.ActiveView.Refresh();
        }

        private void configBtn_Click(object sender, EventArgs e)
        {
            SysConfigWin win = new SysConfigWin(this);
            win.ShowDialog();
        }
        private void printByPageInfo(string title, List<PageInfo> pages, string saveDirPath, string code, List<string>pdfs, double outJdValue)
        {
            for (var i = 0; i < pages.Count; i++)
            {
                PageInfo pageInfo = pages[i];
                string titile = "";
                if (pages.Count > 1)
                {
                    titile = title + "(局部" + pages.Count + "-" + (i + 1) + ")";
                }
                else
                {
                    titile = title;
                }
                updateView(pageInfo.rectange[0], pageInfo.rectange[2], pageInfo.rectange[1], pageInfo.rectange[3], titile, pageInfo.center);
                this.axMapControl.CenterAt(pageInfo.center);
                this.showLineNum(pageInfo.center);
                this.axPageLayoutControl.CenterAt(pageInfo.center);
                this.axPageLayoutControl.ActiveView.Refresh();
                this.axMapControl.ActiveView.Refresh();
                string pdfPath = saveDirPath + code + "-" + i + ".pdf";
                pdfs.Add(pdfPath);
                printService.PrintPro(this.axPageLayoutControl, pdfPath);
            }
        }

        private void showLineNum(IPoint center)
        {
            //获取地图的上下长度
            double mapMinLong = center.X - (mapMaxx - mapMinx) / 2 * Convert.ToInt16(toolConfig.scale);
            double mapMinLat = center.Y - (mapMaxy - mapMiny) / 2 * Convert.ToInt16(toolConfig.scale);
            double xItem = (mapMaxx - mapMinx) / 6;
            double yItem = (mapMaxy - mapMiny) / 6;
            int[]color = new int[]{0, 0, 0};
            for ( int i = 1; i < 6; i++)
            {
                if (lineNumElements.ContainsKey("0" + i))
                {
                    double num = mapMinLat + i * yItem * Convert.ToInt16(toolConfig.scale);
                    ITextElement element = lineNumElements["0" + i];
                    element.Text = num + "\r\n|";
                }
                else
                {
                    double num = mapMinLat + i * yItem * Convert.ToInt16(toolConfig.scale);
                    ITextElement element = printService.drawLine(this.axPageLayoutControl, mapMinx, mapMiny + i * yItem, mapMinx, mapMiny + i * yItem + 2, num + "\r\n|", color, 12, 90);
                    lineNumElements.Add("0" + i, element);
                }
                if (lineNumElements.ContainsKey("1" + i))
                {
                    double num = mapMinLat + i * yItem * Convert.ToInt16(toolConfig.scale);
                    ITextElement element = lineNumElements["1" + i];
                    element.Text = num + "\r\n|";
                }
                else
                {
                    double num = mapMinLat + i * yItem * Convert.ToInt16(toolConfig.scale);
                    ITextElement element = printService.drawLine(this.axPageLayoutControl, mapMaxx, mapMiny + i * yItem, mapMaxx, mapMiny + i * yItem + 2, num + "\r\n|", color, 12, -90);
                    lineNumElements.Add("1" + i, element);
                }
                if (lineNumElements.ContainsKey("2" + i))
                {
                    double num = mapMinLong + i * xItem * Convert.ToInt16(toolConfig.scale);
                    ITextElement element = lineNumElements["2" + i];
                    element.Text = "|\r\n" + num;
                }
                else
                {
                    double num = mapMinLong + i * xItem * Convert.ToInt16(toolConfig.scale);
                    ITextElement element = printService.drawLine(this.axPageLayoutControl, mapMinx + i * xItem, mapMiny - 1.7, mapMinx + i * xItem + 2, mapMiny, "|\r\n" + num, color, 12, 0);
                    lineNumElements.Add("2" + i, element);
                }
                if (lineNumElements.ContainsKey("3" + i))
                {
                    double num = mapMinLong + i * xItem * Convert.ToInt16(toolConfig.scale);
                    ITextElement element = lineNumElements["3" + i];
                    element.Text = num + "\r\n|";
                }
                else
                {
                    double num = mapMinLong + i * xItem * Convert.ToInt16(toolConfig.scale);
                    ITextElement element = printService.drawLine(this.axPageLayoutControl, mapMinx + i * xItem, mapMaxy, mapMinx + i * xItem + 2, mapMaxy, num + "\r\n|", color, 12, 0);
                    lineNumElements.Add("3" + i, element);
                }
            }
            axPageLayoutControl.ActiveView.Refresh();
        }

        private void ydhyBtn_Click(object sender, EventArgs e)
        {
            
        }
        
    }
}
